import { CharacterResolver } from 'lib/character-resolver'

export class Character {
  constructor(public readonly char: string, public width: number = 100) {
    const { ctx, canvas } = this.initCanvas()
    this.ctx = ctx
    this.canvas = canvas
    this.resolver = new CharacterResolver(
      Uint8Array.from(this.imageData.data),
      width
    )
  }

  public resolver: CharacterResolver
  public canvas: HTMLCanvasElement
  private ctx: CanvasRenderingContext2D
  public get imageData() {
    return this.ctx.getImageData(0, 0, this.width, this.width)
  }

  private initCanvas() {
    const canvas = document.createElement('canvas')
    canvas.width = canvas.height = this.width
    const ctx = canvas.getContext('2d')
    if (!ctx) throw new Error('画布上下文未完成初始化')
    ctx.font = `${this.width}px serif`
    ctx.textAlign = 'start'
    ctx.textBaseline = 'top'
    ctx.fillText(this.char[0], 0, 0)
    return { ctx, canvas }
  }
}
